package handlers

import (
	"encoding/json"
	"homepage-backend/internal/config"
	"homepage-backend/internal/models"
	"homepage-backend/internal/services"
	"net/http"
)

// LinkHandler 处理友链请求和管理
func LinkHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		links, err := services.LoadLinks(config.GlobalConfig.LinksFilePath)
		if err != nil {
			http.Error(w, "加载友链数据失败", http.StatusInternalServerError)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(links)
		return
	}
	// 仅签权接口允许增删改
	if r.Method == "POST" || r.Method == "PUT" || r.Method == "DELETE" {
		AdminAuthMiddleware(linkHandlerWrite)(w, r)
		return
	}
}

// linkHandlerWrite 仅用于POST/PUT/DELETE，已通过JWT校验
func linkHandlerWrite(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "POST":
		var link models.Link
		if err := json.NewDecoder(r.Body).Decode(&link); err != nil {
			http.Error(w, "请求数据无效", http.StatusBadRequest)
			return
		}
		err := services.AddLink(config.GlobalConfig.LinksFilePath, link)
		if err != nil {
			http.Error(w, "添加失败", http.StatusInternalServerError)
			return
		}
		w.WriteHeader(http.StatusCreated)
		w.Write([]byte("ok"))
	case "PUT":
		var link models.Link
		if err := json.NewDecoder(r.Body).Decode(&link); err != nil {
			http.Error(w, "请求数据无效", http.StatusBadRequest)
			return
		}
		err := services.UpdateLink(config.GlobalConfig.LinksFilePath, link)
		if err != nil {
			http.Error(w, "修改失败", http.StatusInternalServerError)
			return
		}
		w.Write([]byte("ok"))
	case "DELETE":
		id := r.URL.Query().Get("id")
		if id == "" {
			http.Error(w, "缺少id参数", http.StatusBadRequest)
			return
		}
		err := services.DeleteLink(config.GlobalConfig.LinksFilePath, id)
		if err != nil {
			http.Error(w, "删除失败", http.StatusInternalServerError)
			return
		}
		w.Write([]byte("ok"))
	default:
		http.Error(w, "方法不允许", http.StatusMethodNotAllowed)
	}
}
